package api

import (
	_ "ginfast/api/controller"
	_ "ginfast/api/mall"
	_ "ginfast/api/system"
	_ "ginfast/api/weixin"
	"ginfast/configs"
	"ginfast/middleware"
	"ginfast/pkg/ctx"
	"ginfast/pkg/log"
	"ginfast/views"

	"github.com/gin-gonic/gin"
)

type Options struct {
	Timeout int
	Port    int
	Root    string
	Public  string
}

// New
func Run() error {
	var opts Options
	if err := configs.GViper.UnmarshalKey("serve", &opts); err != nil {
		return err
	}
	// gin.SetMode(gin.ReleaseMode)
	engine := gin.Default()
	// engine.Use(middleware.LoadTLS()) // https
	engine.Use(middleware.Cors()) // 跨域
	views.Static(engine, opts.Root)
	r := engine.Group(opts.Root)
	r.StaticFS("/public", gin.Dir(configs.Public.String(), true))
	ctx.Use(r,
		middleware.UseJWTAuth(r.Group("")),
		// middleware.UseTokenAuth(r.Group("/api")),
	)
	s := ctx.ListenAndServe(engine, opts.Port, opts.Timeout)
	log.Log().Info().Str("addr", s.Addr).Msg(configs.AppName + " start")
	return nil
}

func Shutdown() error {
	return ctx.Release()
}
